package com.wlc.collection.myhashmap;

import com.wlc.collection.Hero;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 王立朝 wanglichao@champion-credit.com
 * @description 比较MyHashMap 和 for 循环哪个查找指定数据快
 * @date 2021-07-13 12:34
 */
public class MyHashMap2 {
    /**
     * 比较MyHashMap 和 for循环查找数据哪个快
     */
    public void method01() {
        ArrayList<Hero> arrayList = new ArrayList<Hero>();
        for (int i = 0; i < 100000; i++) {
            arrayList.add(new Hero("hero-" + ((int) (Math.random() * 9000) + 1000), i));
        }

        // 把集合中对象放在Map中
        MyHashMap myHashMap = new MyHashMap();
        for (Hero hero : arrayList) {
            List<Hero> heroList = (List<Hero>) myHashMap.get(hero.getName());
            if (null == heroList) {
                heroList = new ArrayList<>();
                myHashMap.put(hero.getName(), heroList);
            }
            heroList.add(hero);
        }

        System.out.println("开始查找");
        System.out.println("通过循环查找耗时：");
        findByIteration(arrayList);
        System.out.println("通过MyHashMap 查找");
        findByMap(myHashMap);
    }

    private static List<Hero> findByMap(MyHashMap m) {
        long start = System.currentTimeMillis();
        List<Hero> result = (List<Hero>) m.get("hero-5555");
        long end = System.currentTimeMillis();
        System.out.printf("通过map查找，一共找到%d个英雄，耗时%d 毫秒%n", result.size(), end - start);
        return result;
    }

    private static List<Hero> findByIteration(List<Hero> hs) {
        long start = System.currentTimeMillis();
        List<Hero> result = new ArrayList<>();
        for (Hero h : hs) {
            if (h.getName().equals("hero-5555")) {
                result.add(h);
            }
        }
        long end = System.currentTimeMillis();
        System.out.printf("通过for查找，一共找到%d个英雄，耗时%d 毫秒%n", result.size(), end - start);
        return result;
    }

    public static void main(String[] args) {
        MyHashMap2 myHashMap = new MyHashMap2();
        myHashMap.method01();
    }
}
